package com.ygqh.baby.service.impl;

import com.ygqh.baby.ao.*;
import com.ygqh.baby.constant.Constant;
import com.ygqh.baby.mapper.YgUserBalanceDetailMapper;
import com.ygqh.baby.mapper.YgUserBalanceMapper;
import com.ygqh.baby.model.*;
import com.ygqh.baby.po.*;
import com.ygqh.baby.po.YgUserBalanceDetailExample.Criteria;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.task.YgBalanceTaskService;
import com.ygqh.baby.utils.DateConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 最新改版，账户信息不区分平台
 *
 * @author sunshuo
 * @date 2019/6/18/018 18:21
 */
@Service
public class YgUserBalanceServiceImpl implements YgUserBalanceService {

	@Autowired
	private YgUserBalanceMapper ygUserBalanceMapper;
	@Autowired
	private YgUserBalanceDetailMapper ygUserBalanceDetailMapper;
	@Autowired
	private YgChannelService channelService;
	@Autowired
	private YgUserService userService;
	@Autowired
	private YgAccountDetailService accountDetailService;
	@Autowired
	private YgUserBalanceDetailService ygUserBalanceDetailService;
	@Autowired
	private YgAgentService ygAgentService;
	@Autowired
	private YgOrderService ygOrderService;
	@Autowired
	private YgBalanceTaskService ygBalanceTaskService;
	@Autowired
	private YgUserCultivationDayService ygUserCultivationDayService;
	@Autowired
	private YgAgentInviteRecordService ygAgentInviteRecordService;
	@Autowired
	private YgInformUserService ygInformUserService;

	@Override
	public List<YgUserBalance> find() {
		YgUserBalanceExample example = new YgUserBalanceExample();
		return ygUserBalanceMapper.selectByExample(example);
	}

	@Override
	public int findCount() {
		YgUserBalanceExample example = new YgUserBalanceExample();
		return ygUserBalanceMapper.countByExample(example);
	}

	@Override
	public YgUserBalance findById(Long id) {
		return ygUserBalanceMapper.selectByPrimaryKey(id);
	}

	@Override
	public int save(YgUserBalance ygUserBalance) {
		return ygUserBalanceMapper.insertSelective(ygUserBalance);
	}

	@Override
	public int update(YgUserBalance ygUserBalance) {
		return ygUserBalanceMapper.updateByPrimaryKeySelective(ygUserBalance);
	}

	@Override
	public ResultSet<YgUser> search(QueryInfo queryInfo, String userName, String sourceCode, String q, Date startTime,
									Date endTime, String userType, Long userId) {
		List<YgUser> list = ygUserBalanceMapper.selectSuper(queryInfo, userName, sourceCode, q, startTime, endTime,
				userType, userId);
		int count = ygUserBalanceMapper.countSuper(userName, sourceCode, q, startTime, endTime, userType, userId);
		ResultSet<YgUser> resultSet = new ResultSet<YgUser>(count, list);
		return resultSet;
	}

	@Override
	public ResultSet<YgUser> search(QueryInfo queryInfo, String userName, String sourceCode, String q,
									String userType, Long userId) {
		return this.search(queryInfo, userName, sourceCode, q, null, null, userType, userId);
	}

	@Override
	public int saveOrUpdate(YgUserBalance ygUserBalance) {
		int r = 0;
		if (ygUserBalance.getId() != null) {
			r = this.update(ygUserBalance);
		} else {
			r = this.save(ygUserBalance);
		}
		return r;
	}

	@Override
	public ResultSet<YgUserBalanceDetail> searchBalanceDetail(QueryInfo queryInfo, BalanceType balanceType, Long userId,
															  String platformNo) {
		String balanceTypeName = balanceType == null ? null : balanceType.name();
		List<YgUserBalanceDetail> list = ygUserBalanceDetailMapper.selectBalanceDetail(queryInfo, balanceTypeName,
				userId, platformNo);
		int row = ygUserBalanceDetailMapper.countBalanceDetail(balanceTypeName, userId, platformNo);
		return new ResultSet<>(row, list);
	}

	@Override
	public YgUserBalance findByUserId(Long userId) {
		return findByUserId(userId, Constant.YIIGOO_PLATFORM_NO);
	}

	@Override
	public YgUserBalance findByUserId(Long userId, String platformNo) {
		if (StringUtils.isBlank(platformNo)) {
			platformNo = Constant.YIIGOO_PLATFORM_NO;
		}
		YgUserBalanceExample example = new YgUserBalanceExample();
		example.createCriteria().andUserIdEqualTo(userId).andPlatformNoEqualTo(platformNo);
		List<YgUserBalance> list = ygUserBalanceMapper.selectByExample(example);
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public List<YgUserBalanceDetail> findUserBalanceDetailByUserId(Long userId) {
		return ygUserBalanceDetailMapper.findUserBalanceDetailByUserId(userId, BalanceType.Balance);
	}

	@Override
	public List<YgUserBalanceDetailModel> findBalanceDetailsByType(QueryInfo queryInfo, Long userId, String balance, String preIncome) {
		return findBalanceDetailsByType(queryInfo, userId, balance, preIncome, Constant.YIIGOO_PLATFORM_NO);
	}

	@Override
	public List<YgUserBalanceDetailModel> findBalanceDetailsByType(QueryInfo queryInfo, Long userId, String balance, String preIncome, String platformNo) {
		return ygUserBalanceDetailMapper.selectBalanceDetailByType(queryInfo, userId, balance, preIncome, platformNo);
	}

	@Override
	public YgUserBalanceOrderDetailModel findOrderBalanceDetail(Long balanceDetailId, Long userId) {
		return ygUserBalanceDetailMapper.selectOrderBalanceDetail(balanceDetailId, userId);
	}

	@Override
	public YgUserBalanceOrderInfo findOrderBalanceDetailV2(String ubdOrderId, BalanceType balanceType,
														   OperationType operationType, Long userId) {
		return ygUserBalanceDetailMapper.selectOrderBalanceDetailV2(ubdOrderId, balanceType, operationType.name(), userId);
	}

	@Override
	public List<YgUserBalanceOrderModel> findOrderList(QueryInfo queryInfo, String sourceCode) {
		return ygUserBalanceMapper.selectOrderList(queryInfo, sourceCode);
	}

	@Override
	public int addBalacneDetailByBatch(List<YgUserBalanceDetail> detailList) {
		if (detailList != null && detailList.size() > 0) {
			return ygUserBalanceDetailMapper.insertBalacneDetailByBatch(detailList);
		}
		return 0;
	}

	@Override
	public int updateUserBalanceByTask(List<YgUserBalance> balanceList) {
		return ygUserBalanceMapper.updateUserBalanceByTask(balanceList);
	}

	@Override
	public int updateUserBalancePrice(List<YgUserBalance> balanceList) {
		if (CollectionUtils.isEmpty(balanceList)) {
			return 0;
		}
		return ygUserBalanceMapper.updateUserBalancePrice(balanceList);
	}

	@Override
	public int addPriceTypeToBalance() {
		return ygUserBalanceDetailMapper.addPriceTypeToBalance();
	}

	@Override
	public List<YgUserBalanceDetail> findListByPriceTypeAndOrderIds(BalanceType balanceType, Long[] orderIds) {
		return ygUserBalanceDetailMapper.findListByPriceTypeAndOrderIds(balanceType, orderIds);
	}

	@Override
	public List<YgUserBalance> findListByUserIds(List<Long> userIds) {
		return ygUserBalanceMapper.findListByUserIds(userIds);
	}

	@Override
	public ResultSet<YgCompanyBalanceDetailModel> findCompanyPreIncomeList(QueryInfo queryInfo, Long userId) {
		List<String> sourceCodeList = channelService.findSourceCodeWithParent(userId);
		List<YgCompanyBalanceDetailModel> companyBalanceDetailModels;
		ResultSet<YgCompanyBalanceDetailModel> resultSet;
		if (!sourceCodeList.isEmpty()) {
			// 领导查看的明细页
			companyBalanceDetailModels = ygUserBalanceDetailMapper.findCompanyListBySourceCodes(queryInfo, sourceCodeList, BalanceType.PreIncome.name());
			Map<String, Object> map = ygUserBalanceDetailMapper.findCompanyListBySourceCodesCount(sourceCodeList, BalanceType.PreIncome.name());
			long count = (long) map.get("count");
			resultSet = new ResultSet<>(count, companyBalanceDetailModels);
			resultSet.setExt(map.get("totalMoney"));
		} else {
			// 普通员工查看明细
			companyBalanceDetailModels = ygUserBalanceDetailMapper.findCompanyListByUserId(queryInfo, userId, BalanceType.PreIncome.name());
			Map<String, Object> map = ygUserBalanceDetailMapper.findCompanyListByUserIdCount(userId, BalanceType.PreIncome.name());
			long count = (long) map.get("count");
			resultSet = new ResultSet<>(count, companyBalanceDetailModels);
			resultSet.setExt(map.get("totalMoney"));
		}
		return resultSet;
	}

	@Override
	public ResultSet<YgCompanyBalanceDetailModel> findCompanyPreIncomeListByUserId(QueryInfo queryInfo, Long userId, BalanceType type) {
		List<YgCompanyBalanceDetailModel> companyBalanceDetailModels;
		ResultSet<YgCompanyBalanceDetailModel> resultSet;
		companyBalanceDetailModels = ygUserBalanceDetailMapper.findCompanyListByUserId(queryInfo, userId, type.name());
		Map<String, Object> map = ygUserBalanceDetailMapper.findCompanyListByUserIdCount(userId, type.name());
		long count = (long) map.get("count");
		resultSet = new ResultSet<>(count, companyBalanceDetailModels);
		resultSet.setExt(map.get("totalMoney"));
		return resultSet;
	}

	@Override
	public ResultSet<YgCompanyBalanceDetailModel> findCompanyBalanceList(QueryInfo queryInfo, Long userId) {
		YgUser user = userService.findById(userId);
		List<String> sourceCodeList = Arrays.asList(user.getSourceCode());
		List<YgCompanyBalanceDetailModel> companyBalanceDetailModels;
		ResultSet<YgCompanyBalanceDetailModel> resultSet;
		if (!sourceCodeList.isEmpty()) {
			// 领导查看的明细页
			companyBalanceDetailModels = ygUserBalanceDetailMapper.findCompanyListBySourceCodes(queryInfo, sourceCodeList, BalanceType.Balance.name());
			Map<String, Object> map = ygUserBalanceDetailMapper.findCompanyListBySourceCodesCount(sourceCodeList, BalanceType.Balance.name());
			long count = (long) map.get("count");
			resultSet = new ResultSet<>(count, companyBalanceDetailModels);
			resultSet.setExt(map.get("totalMoney"));
		} else {
			// 普通员工查看明细
			companyBalanceDetailModels = ygUserBalanceDetailMapper.findCompanyListByUserId(queryInfo, userId, BalanceType.Balance.name());
			Map<String, Object> map = ygUserBalanceDetailMapper.findCompanyListByUserIdCount(userId, BalanceType.Balance.name());
			long count = (long) map.get("count");
			resultSet = new ResultSet<>(count, companyBalanceDetailModels);
			resultSet.setExt(map.get("totalMoney"));
		}
		return resultSet;

	}

	@Override
	public List<YgCompanyBalanceCollectModel> findPreIncomeCompanyMoneyCollectByUser(Long userId) {
		List<String> sourceCodeList = channelService.findSourceCodeWithParent(userId);
		if (sourceCodeList.isEmpty()) {
			return new ArrayList<>();
		}
		return ygUserBalanceDetailMapper.findCompanyMoneyCollectByUser(userId, BalanceType.PreIncome.name(), sourceCodeList);
	}

	@Override
	public List<YgCompanyBalanceCollectModel> findBalanceCompanyMoneyCollectByUser(Long userId) {
		List<String> sourceCodeList = channelService.findSourceCodeWithParent(userId);
		return ygUserBalanceDetailMapper.findCompanyMoneyCollectByUser(userId, BalanceType.Balance.name(), sourceCodeList);
	}

	@Override
	public Map<String, Object> findCompaneyPreIncomeAndBalanceSum(Long userId) {
		List<String> sourceCodeList = channelService.findSourceCodeWithParent(userId);
		YgUser user = userService.findById(userId);
		if (sourceCodeList.isEmpty()) {
			// 如果不是领导

			sourceCodeList.add(user.getSourceCode());
		}
		Map<String, Object> result = new HashMap<String, Object>();
		if (sourceCodeList.isEmpty()) {
			result.put("preInComeSum", 0);
			result.put("balanceSum", 0);
			return result;
		}
		Map<String, Object> preIncomeSum = ygUserBalanceDetailMapper.findCompanyListBySourceCodesCountWithPrimary(sourceCodeList);
		Map<String, Object> balanceSum = ygUserBalanceDetailMapper.findCompanyListBySourceCodesCountWithPrimary(Arrays.asList(user.getSourceCode()));
		Map<String, Object> order = ygUserBalanceDetailService.getOrderPriceBySourceCode(sourceCodeList);
		result.put("preInComeSum", preIncomeSum.get("preInComeSum"));
		result.put("balanceSum", balanceSum.get("balanceSum"));
		result.put("orderPrice", order.get("orderPrice"));
		return result;
	}

	@Override
	public BiChannelModel findChannelBi(String sourceCode) {
		return ygUserBalanceDetailMapper.selectChannelBi(sourceCode);
	}

	@Override
	public int reduceAcountPrice(Long userId, BigDecimal accountPrice) {
		return reduceAcountPrice(userId, accountPrice, Constant.YIIGOO_PLATFORM_NO);
	}

	@Override
	public int reduceAcountPrice(Long userId, BigDecimal accountPrice, String platformNo) {
		if (StringUtils.isBlank(platformNo)) {
			platformNo = Constant.YIIGOO_PLATFORM_NO;
		}
		return ygUserBalanceMapper.reduceAcountPrice(userId, accountPrice, platformNo);
	}

	@Override
	public int backAcountPrice(Long userId, BigDecimal accountPrice) {
		return backAcountPrice(userId, accountPrice, Constant.YIIGOO_PLATFORM_NO);
	}

	@Override
	public int backAcountPrice(Long userId, BigDecimal accountPrice, String platformNo) {
		if (StringUtils.isBlank(platformNo)) {
			platformNo = Constant.YIIGOO_PLATFORM_NO;
		}
		return ygUserBalanceMapper.backAcountPrice(userId, accountPrice, platformNo);
	}

	@Override
	public Message recharge(String phone, BigDecimal price, String remark, String createBy) {

		try {

			YgUser user = userService.findByUserName(phone);
			if (user == null) {
				return Message.error("手机号码不存在");
			}

			if (price.compareTo(new BigDecimal(0)) == -1 || price.compareTo(new BigDecimal(0)) == 0) {
				return Message.error("充值金额需大于0");
			}

			this.backAcountPrice(user.getId(), price);

			YgUserBalanceDetail ygUserBalanceDetail = new YgUserBalanceDetail();
			ygUserBalanceDetail.setUserId(user.getId());
			ygUserBalanceDetail.setBalancePrice(price);
			ygUserBalanceDetail.setPriceType(BalanceType.Balance);
			ygUserBalanceDetail.setOperation(OperationType.Recharge.getTitle());
			ygUserBalanceDetail.setOperationType(OperationType.Recharge);
			ygUserBalanceDetail.setCreateBy(createBy);
			ygUserBalanceDetail.setCreateTime(new Date());
			ygUserBalanceDetail.setRemark(remark);
			ygUserBalanceDetailService.save(ygUserBalanceDetail);
		} catch (Exception e) {
			e.printStackTrace();
			return Message.error("操作失败");
		}
		return Message.success("操作成功");
	}

	@Override
	public Message redPacketRecharge(String phone, BigDecimal price, String remark, String createBy) {
		try {

			YgUser user = userService.findByUserName(phone);

			this.backAcountPrice(user.getId(), price);

			this.addBalanceDetail(user.getId(), remark, price, BalanceType.Balance, OperationType.RedPacket, "红包转可提现历史数据");

			YgAccountDetail accountDetail = new YgAccountDetail();
			accountDetail.setUserId(user.getId());
			accountDetail.setPrice(price);
			accountDetail.setPriceType(PriceType.RedPacket);
			accountDetail.setCreateTime(new Date());
			accountDetail.setCreateBy(createBy);
			accountDetail.setRemark(remark);
			accountDetailService.save(accountDetail);
		} catch (Exception e) {
			e.printStackTrace();
			return Message.error("操作失败");
		}
		return Message.success("操作成功");
	}

	@Override
	public Message incomeRecharge(Long userId, BigDecimal price, OperationType operationType, String relationId, String remark, String createBy) {
		try {
			this.backAcountPrice(userId, price);

			YgUserBalanceDetail detail = new YgUserBalanceDetail();
			detail.setUserId(userId);
			detail.setBalancePrice(price);
			detail.setPriceType(BalanceType.Balance);
			detail.setOperation(operationType.getTitle());
			detail.setOperationType(operationType);
			detail.setOrderId(relationId);
			detail.setCreateTime(new Date());
			detail.setRemark(remark);
			ygUserBalanceDetailService.save(detail);
		} catch (Exception e) {
			e.printStackTrace();
			return Message.error("操作失败");
		}
		return Message.success("操作成功");
	}

	@Override
	public Message updateRate(Long userId, BigDecimal shareRate, BigDecimal foreverRate) {
		YgUser user = new YgUser();
		user.setId(userId);
		user.setShareRate(shareRate);
		user.setForeverRate(foreverRate);
		userService.updateUserInfo(user);
		return Message.success("更新成功");
	}

	@Override
	public int backAcountPriceBatch(List<YgOrder> orderList) {
		if (orderList != null && orderList.size() > 0) {
			return ygUserBalanceMapper.backAcountPriceBatch(orderList);
		}
		return 0;

	}

	@Override
	public List<YgUserBalanceDetail> findBalanceForCommissionDetail(Long userId) {
		return ygUserBalanceDetailMapper.selectBalanceForCommissionDetail(userId);
	}

	@Override
	public Map<String, Object> findTotalBalancePriceForCommission(Long userId) {
		return findTotalBalancePriceForCommission(userId, Constant.YIIGOO_PLATFORM_NO);
	}

	@Override
	public Map<String, Object> findTotalBalancePriceForCommission(Long userId, String platformNo) {
		return ygUserBalanceDetailMapper.selectTotalBalancePriceForCommission(userId, platformNo);
	}

	@Override
	public int updateBalanceDetailByCommission(Long userId, Long commissionId, CommissionStatus commissionStatus,
											   Boolean isApply, Long maxId, String platformNo) {
		return ygUserBalanceDetailMapper.updateBalanceDetailByCommission(userId, commissionId, commissionStatus,
				isApply, maxId, platformNo);
	}

	@Override
	public YgUserBalanceDetail findBalanceDetail(Long userId, Long orderId, RebateType rebateType, BalanceType balanceType) {
		YgUserBalanceDetailExample example = new YgUserBalanceDetailExample();
		Criteria criteria = example.createCriteria();
		criteria.andUserIdEqualTo(userId).andOrderIdEqualTo(orderId.toString()).andPriceTypeEqualTo(balanceType.name()).andRebateTypeEqualTo(rebateType.name());
		List<YgUserBalanceDetail> list = ygUserBalanceDetailMapper.selectByExample(example);
		if (!CollectionUtils.isEmpty(list)) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public int addBalanceDetail(Long userId, String orderId, BigDecimal accountPrice, BalanceType balance, OperationType operationType, String remark) {
		return addBalanceDetail(userId, orderId, accountPrice, balance, operationType, remark, Constant.YIIGOO_PLATFORM_NO);
	}

	@Override
	public int addBalanceDetail(Long userId, String orderId, BigDecimal accountPrice, BalanceType balance,
								OperationType operationType, String remark, String platformNo) {
		if (StringUtils.isBlank(platformNo)) {
			platformNo = Constant.YIIGOO_PLATFORM_NO;
		}
		YgUserBalanceDetail balanceDetail = new YgUserBalanceDetail();
		balanceDetail.setUserId(userId);
		balanceDetail.setOrderId(orderId);
		balanceDetail.setBalancePrice(accountPrice);
		balanceDetail.setPriceType(balance);
		balanceDetail.setOperation(operationType.getTitle());
		balanceDetail.setOperationType(operationType);
		balanceDetail.setCreateTime(new Date());
		balanceDetail.setRemark(remark);
		balanceDetail.setPlatformNo(platformNo);
		return ygUserBalanceDetailMapper.insertSelective(balanceDetail);
	}

	@Override
	public List<YgUserBalanceDetail> findBalanceDetailByCommissionId(Long commissionId, Long userId) {
		return findBalanceDetailByCommissionId(commissionId, userId, Constant.YIIGOO_PLATFORM_NO);
	}

	@Override
	public List<YgUserBalanceDetail> findBalanceDetailByCommissionId(Long commissionId, Long userId, String platformNo) {
		List<String> str = new ArrayList<String>();
		str.add(OperationType.Withdraw.name());
		str.add(OperationType.WithdrawFail.name());
		YgUserBalanceDetailExample example = new YgUserBalanceDetailExample();
		Criteria criteria = example.createCriteria().andUserIdEqualTo(userId).andCommissionIdEqualTo(commissionId)
				.andOperationTypeNotIn(str);
		if (StringUtils.isNotBlank(platformNo)) {
			criteria.andPlatformNoEqualTo(platformNo);
		}
		return ygUserBalanceDetailMapper.selectByExample(example);
	}

	@Override
	public List<BalanceDiff> findDifference(BalanceType bType) {
		return findDifference(bType, false);
	}

	@Override
	public List<BalanceDiff> findDifference(BalanceType bType, boolean splitPlatform) {
		return ygUserBalanceMapper.selectDifference(bType.name(), splitPlatform);
	}

	@Override
	public Message checkBalance(BigDecimal checkPrice, Long userId) {
		YgUserBalance balance = this.findByUserId(userId);
		if (balance.getBalancePrice().compareTo(checkPrice) < 0) {
			return Message.error("成长基金不足，实际成长金额：" + balance.getBalancePrice(), checkPrice);
		}
		return Message.success(balance.getBalancePrice());
	}

	@Override
	public int resetUserBalance(BalanceType balanceType, List<Long> userIds) {
		return resetUserBalance(balanceType, userIds, false);
	}

	@Override
	public int resetUserBalance(BalanceType balanceType, List<Long> userIds, boolean splitPlatform) {
		if (CollectionUtils.isEmpty(userIds)) {
			throw new RuntimeException("用户id不能为空。");
		}

		return ygUserBalanceMapper.resetUserBalance(balanceType == null ? null : balanceType.name(), userIds, splitPlatform);
	}

	@Override
	public Map<String, Object> getUserShareOrderPrice(Long userId) {
		Map<String, Object> data = new HashMap<>();
		BigDecimal orderPrice = new BigDecimal("0.00");
		BigDecimal keepPrice = new BigDecimal("0.00");
		Date agentStartDate = null;
		YgUser user = userService.findById(userId);
		if (user.isUserAgent() || user.isUserGroup()) {
			YgAgent agent = ygAgentService.findValidByUserId(user.getId(), user.getUserType());
			if (agent != null) {
				agentStartDate = agent.getCheckTime();
				if (agentStartDate != null) {
					Date startDate = DateConvertUtils.getMonthStartDate(new Date());
					if (agentStartDate.after(startDate)) {
						startDate = agentStartDate;
					}
					orderPrice = ygUserCultivationDayService.getUserShareOrderPrice(user,
							DateConvertUtils.getDateStart(startDate), null);
					/*keepPrice = calculateKeepPrice(orderPrice, record);*/
				}
			}
		}
		data.put("agentStartDate", agentStartDate);
		data.put("orderPrice", orderPrice);
		data.put("keepPrice", keepPrice);
		return data;
	}

	/**
	 * 计算保级金额
	 * @param orderPrice
	 * @param record
	 * @return
	 */
	private BigDecimal calculateKeepPrice(BigDecimal orderPrice, YgAgentInviteRecord record) {
		BigDecimal keepPrice = new BigDecimal("0.00");
		BigDecimal minPrice = new BigDecimal("500.00");
		if (orderPrice.compareTo(minPrice) >= 0) { // 达到最低耕耘要求
			return keepPrice;
		}
		Date now = new Date();
		if (now.after(DateConvertUtils.getMonthStartDate(record.getExpireTime()))) {
			keepPrice = minPrice.subtract(orderPrice);
		}
		return keepPrice;
	}

	@Override
	public List<YgUserShareOrderModel> getUserShareOrder(QueryInfo queryInfo, YgUser ygUser) {
		if (ygUser.isUserAgent() || ygUser.isUserGroup()) {
			List<YgUserShareOrderModel> result = new ArrayList<>();
			YgAgent agent = ygAgentService.findByRecent(ygUser.getId(), ygUser.getUserType());
			Date checkTime = agent.getCheckTime();
			Date cancelTime = agent.getCancelTime() == null ? DateConvertUtils.getDateStart(new Date()) : agent.getCancelTime();
			OrderStatus[] orderStatus = new OrderStatus[] { OrderStatus.WaitingCheck, OrderStatus.WaitingSend, OrderStatus.WaitingSign, OrderStatus.TradeSuccess };
			List<YgOrder> shareList = ygOrderService.findByPaidTimeHasDetail(checkTime, cancelTime, ygUser.getSourceCode(), orderStatus);
			List<YgOrder> agentList = ygOrderService.findAgentOrderByPaidTimeHasDetail(checkTime, cancelTime, ygUser.getId(), orderStatus);
			if (ygUser.isUserGroup()) {
				List<YgOrder> groupMemberList = ygOrderService.findGroupMemberOrderByPaidTimeHasDetail(agent.getCheckTime(), cancelTime, ygUser.getGroupTag(),
						orderStatus);

				shareList.addAll(groupMemberList);
			}
			shareList.addAll(agentList);
			if (!CollectionUtils.isEmpty(shareList)) {
				BigDecimal zero = new BigDecimal("0.00");
				List<Long> orderIds = shareList.stream().map(o -> o.getOrderId()).collect(Collectors.toList());
				List<YgOrder> returnList = ygOrderService.findRODByOrderId(orderIds, ReturnType.Return, ReturnStatus.Complete);
				for (YgOrder o : shareList) {

					Date date = DateConvertUtils.parse("2018-01-01", DateConvertUtils.DATE_FORMAT);
					Boolean onlyYiigoo = true;
					if (o.getPaidTime().before(date)) {
						onlyYiigoo = false;
					}

					BigDecimal oPrice = ygBalanceTaskService.getPaidPrice(o, onlyYiigoo);
					if (oPrice.compareTo(zero) == 0) {
						continue;
					}
					BigDecimal roPrice = zero;
					if (!CollectionUtils.isEmpty(returnList)) {
						List<YgOrder> collect = returnList.stream().filter(ro -> o.getOrderId().equals(ro.getOrderId())).collect(Collectors.toList());
						if (!CollectionUtils.isEmpty(collect)) {
							YgOrder ro = collect.get(0);
							roPrice = ygBalanceTaskService.getReturnPrice(ro, onlyYiigoo);
						}
					}
					if (oPrice.compareTo(roPrice) <= 0) {
						continue;
					}
					YgUserShareOrderModel model = new YgUserShareOrderModel();
					model.setNickName(o.getNickName());
					model.setUserName(o.getUserName());
					model.setOrderId(o.getOrderId());
					model.setTotalPrice(oPrice);
					model.setReturnPrice(roPrice);
					model.setCreateTime(o.getCreateTime());
					result.add(model);
				}

			}
			return result.stream().sorted(Comparator.comparing(YgUserShareOrderModel::getOrderId).reversed()).collect(Collectors.toList());
		}
		return null;
	}

	@Override
	public YgUserShareOrderModel findShareOrderInfo(Long orderId) {
		return null;
	}

	@Override
	public int transferBalance(Long sourceUserId, Long targetUserId) {
		ygUserBalanceDetailService.transferBalanceDetail(sourceUserId, targetUserId);
		return this.resetUserBalance(targetUserId);
	}

	@Override
	public int resetUserBalance(Long... userIds) {
		if (userIds == null || userIds.length == 0) {
			throw new RuntimeException("用户id不能为空");
		}
		return this.resetUserBalance(null, Arrays.asList(userIds));

	}

	@Override
	public void processUserBalance(Long userId) {
		processUserBalance(userId, Constant.YIIGOO_PLATFORM_NO);
	}

	@Override
	public void processUserBalance(Long userId, String platformNo) {
		YgUserBalance balance = this.findByUserId(userId, platformNo);
		if (balance == null) {
			this.save(new YgUserBalance(userId, platformNo));
		}
	}
}
